import numpy as np

from dao.recommend_mapper import recommend_entity_by_UID
from dao.recommend_mapper import transform
from utils.redis_util import redis_template

word_prefix = 'word-'
data_idx_prefix = 'data-map-'


def news_words_id_to_words(news_words):
    title = ''
    complete = False
    for i in range(len(news_words) - 1):
        if news_words[i] == 0:
            title = title[:-1]
            complete = True
            break
        # 从第3个字符开始,倒数第2个字符结束，前2个字符为b',最后一个字符为'
        title = title + str(redis_template.get(word_prefix + str(news_words[i])))[2:-1] + ' '
    if complete is False:
        title = title + str(redis_template.get(word_prefix + str(news_words[-1])))[2:-1]
    return title


def get_recommend_result(uid):
    labels, scores = recommend_entity_by_UID(uid)
    # 挑选出用户会点击的label并从中选出最大的k个推荐给用户
    label_one_idx = np.where(labels == 1.0)[0]
    label_zero_idx = np.where(labels == 0.0)[0]
    # 先把label为0的分数置为0避免影响最后结果
    scores[label_zero_idx] = 0.0
    k = min(10, label_one_idx.shape[0])
    res = np.argpartition(scores, -k)[-k:]
    res = [redis_template.get(data_idx_prefix + str(item)) for item in res]
    res = transform(res)
    ans = []
    for data in res['news_words']:
        ans.append(news_words_id_to_words(data))
    return ans


if __name__ == '__main__':
    get_recommend_result(0)
